package com.zwl.smartplatform.controller;

import com.zwl.smartplatform.dto.R;
import com.zwl.smartplatform.events.UserLoginEvent;
import com.zwl.smartplatform.pojo.User;
import com.zwl.smartplatform.service.UserService;
import com.zwl.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/users")
public class UserController {

    private ApplicationContext context;

   private UserService userService;

   @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired()
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/user")
    public R registry(@RequestBody User user){
       //insert只有两种结果 一个是抛出异常 一个是插入成功
        //update有条件 所以他的结果有三种 一个是抛出异常 一种是更新成功数据 一种是更新成功0条
       userService.addUser(user);
       return R.setOK();
    }

    @PostMapping("/login")
    public R login(String username, String password, HttpSession session){

        User user = userService.login(username, password);
        session.setAttribute("user",user);
        context.publishEvent(new UserLoginEvent());
        return R.setOK(user.getUsername());
    }
}
